<script setup>
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components'
import { PieChart, BarChart, LineChart } from 'echarts/charts'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
  BarChart,
  GridComponent,
  LineChart,
  UniversalTransition,
])

// 定义props,接受自定义配置项
const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
})

// 定义默认配置项
const defaultOptions = {
  grid: {
    left: '10%',
    right: '3%',
    bottom: '15%',
  },
}

const finalOptions = computed(() => {
  return { ...defaultOptions, ...props.options }
})

// 初始化echarts
let chartInstance = null
const chartDom = useTemplateRef('main')
const initChart = () => {
  chartInstance = echarts.init(chartDom.value)
  props.options && chartInstance.setOption(finalOptions.value)
}

// 监听窗口大小变化，调整图表大小
const observer = ref(null)
const resizeChart = () => {
  chartInstance && chartInstance.resize()
}

// 组件挂载后初始化echarts
onMounted(() => {
  initChart()
  observer.value = new ResizeObserver(resizeChart)
  observer.value.observe(chartDom.value)
})

// 组件卸载前销毁echarts实例
onBeforeUnmount(() => {
  chartInstance && chartInstance.dispose()
  chartInstance = null
  observer.value && observer.value.disconnect()
})

// 监听options的变化，更新echarts配置项
watch(
  () => props.options,
  newVal => {
    if (chartInstance) {
      nextTick(() => {
        chartInstance.setOption(newVal)
      })
    }
  }
)
</script>

<template>
  <!-- 准备echarts图表的容器 -->
  <div ref="main" :style="{ width: '100%', height: '100%' }"></div>
</template>

<style scoped lang="less"></style>
